<template>
  <div class="slider-wrapper">
    <h2>1到100之间：{{ num }}</h2>
    <h3>5到15之间：{{ 5+ num / 100 * (15-5) }}</h3>
    <!-- a+num/100(b-a) -->
    <div
      class="slider"
      @click.self="onClick"
    >
      <div
        :style="{'left':num+'%','transition':isTouch?'none':'.3s'}"
        @touchstart.prevent="onStart"
        @touchmove.prevent="onMove"
        @touchend.prevent="onEnd"
        @touchcancel.prevent="onEnd"
      ></div>
    </div>
  </div>
</template>

<script>
  export default {
    data(){
      return {
        num:0,//0-100
        startNum:0,//拖动开始时num的值
        startX:0,//滑块的初始位置
        endX:0, //滑块的结束位置
        isTouch:false //是否正在拖动
      }
    },
    methods:{
      onClick(event){
        this.num=100 * (event.offsetX/200)
      },
      setNum(){
        const limit = n => Math.max(0,Math.min(100,n));
        this.num =  limit(Math.round(this.startNum + 100 * (this.endX-this.startX)/200))
      },
      onStart(event){
        const point = event.touches[0];
        this.startX = point.clientX;
        this.startNum = this.num;
        this.isTouch=true;
      },
      onMove(event){
        const point = event.touches[0];
        this.endX= point.clientX;
        this.setNum();
      },
      onEnd(){
        this.setNum();
        this.isTouch=false
      }
    }
  }
</script>

<style lang="sass" scoped>
.slider
  position: relative
  width: 200px
  height: 50px
  margin: 0 auto
  &:before
    content: ""
    position: absolute
    top: 50%
    left: 0
    transform: translateY(-50%)
    background: #ccc
    width: 100%
    height: 3px
  div
    position: absolute
    top: 10%
    left: 0
    right: 0
    bottom: 0
    margin-left: -15px
    border-radius: 50%
    width: 30px
    height: 30px
    background: #fff
    box-shadow: 0 0 5px 0 #ccc
</style>
